<template>
	<div class="login_container">
		<div class="login-box">
			<el-form :rules="rulesLogin" label-width="65px" class="login_form" :model="formLogin" ref="loginRef">
				<el-form-item label="用户名" prop="name">
					<el-input v-model="formLogin.name"></el-input>
				</el-form-item>
				
				<el-form-item label="密 码" prop="password">
					<el-input v-model="formLogin.password"></el-input>
				</el-form-item>
				
				<el-form-item class="btns">
					<el-button type="success" @click="register()">注册</el-button>
					<el-button type="primary" @click="loginV()">登录</el-button>
					<el-button type="danger" @click="resetForm('loginRef')">重置</el-button>
				</el-form-item>
			   
			</el-form>
		</div>
		
	</div>
</template>

<script>
	export default {
		data(){
			return {
				//表单数据绑定对象
				formLogin: {
					name: 'tom',
					password: '123'
				},
				// 表单验证
				rulesLogin: {
					name: [
						{ required: true, message: '请输入用户名', trigger: 'blur' },
						{ min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
					],
					password: [
						{ required: true, message: '请输入密码', trigger: 'blur' },
						{ min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
					]
				},

			};
		},
		methods: {
			resetForm(refobj){
				this.$refs[refobj].resetFields();
				// console.log(this)
			},
			loginV(){
				this.$refs.loginRef.validate(async(valida)=>{
					if(!valida) return;
					let data = new FormData();
				    data.append('name',this.formLogin.name);
				    data.append('password',this.formLogin.password);
					// console.log(data);
					// this.formLogin是对象不能直接传递
					const {data: res} = await this.$http.post("userapi/login/?action=login", data);
					console.log(res);
					if(res.status == 1000){
						// console.log("登陆成功");
						window.sessionStorage.setItem("token", res.token);
						window.localStorage.setItem("token", res.token);
						window.sessionStorage.setItem("username", this.formLogin.name);
						window.sessionStorage.setItem("u_id", res.u_id);
						if(res.role == 0){
							this.$router.push("/admin/home");
						}
						else if(res.role == 1){
							this.$router.push("/seller/home");
						}
						else if(res.role == 2){
							this.$router.push("/buyer/home");
						}
						
					}
					else {
						this.$message.error("登录失败");
					}
				})
			},
			register(){
				this.$router.push('/register')
			}
		}
	}
</script>

<style lang="less" scoped="scoped">
	.login_container{
		background-color: #46b989;
		height: 100%;
	}
	.login-box{
		width: 450px;
		height: 300px;
		border-radius: 3px;
		background-color: white;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
	}
	.btns{
		display: flex;
		justify-content: flex-end;
	}
	.login_form{
		position: absolute;
		bottom: 20px;
		width: 100%;
		padding: 0 20px;
		box-sizing: border-box;
	}
</style>
